package Libs.Componentes.Visuais
{
    import flash.display.DisplayObject;
    import flash.events.Event;
    import flash.events.ProgressEvent;
    import flash.events.TimerEvent;
    import flash.net.FileReference;
    import flash.net.URLRequest;
    import flash.net.URLRequestMethod;
    import flash.utils.Timer;
    
    import mx.containers.TitleWindow;
    import mx.controls.ProgressBar;
    import mx.core.Application;
    import mx.managers.PopUpManager;
    import mx.messaging.config.ServerConfig;

    public class UploadFile
    {
        /**
        * Define qual o arquivo .NET será chamado para realizar o upload físico do arquivo
        */
        private var UPLOAD_URL:String;	
        private var _fileReference:FileReference;
        private var _progressBar:ProgressBar = new ProgressBar();
        private var _titleWindow:TitleWindow;
        private var _myTimer1:Timer;
        private var _request:URLRequest;
        private var _selecionado:Boolean = false;
		
		/**
        * Inicializa o FileReference e adiciona os EventListeners 
        */
        public function UploadFile():void 
        {
            _fileReference = new FileReference();
            _fileReference.addEventListener(Event.SELECT, selectHandler);
            _fileReference.addEventListener(Event.OPEN, openHandler);
            _fileReference.addEventListener(ProgressEvent.PROGRESS, progressHandler);
            _fileReference.addEventListener(Event.COMPLETE, completeHandler);
            
            var urlServidor:String = ObterEnderecoServidor(ServerConfig.getChannel("my-amf").endpoint);
			this.UPLOAD_URL = (urlServidor + "UploadFile.ashx");
			
			_myTimer1 = new Timer(3000, 1);
			_myTimer1.addEventListener(TimerEvent.TIMER_COMPLETE, timerHandler1);
        }
        
        private function ObterEnderecoServidor(enderecoCompleto:String):String
        {
        	while((enderecoCompleto.substring(enderecoCompleto.length - 1, enderecoCompleto.length) != "/"))
        	{
        		enderecoCompleto = enderecoCompleto.substring(0, enderecoCompleto.length - 1)
    		}
        	
        	return enderecoCompleto;
        }   

		public function set UrlUpload(url:String):void
		{
			this.UPLOAD_URL = url;
		}
		
		public function get UrlUpload():String
		{
			return this.UPLOAD_URL;
		}

        /**
        * Prepara o label da barra de progressão para informar o % de envio do arquivo
        */
        private function openHandler(event:Event):void 
        {
            _progressBar.label = "Carregando %3%%";
        }

        /**
        * Atualiza o percentual concluído.
        */
        private function progressHandler(event:ProgressEvent):void
        {
            _progressBar.setProgress(event.bytesLoaded, event.bytesTotal);
        }

        /**
         * Após o upload completo, é alterado o label da barra de progressão, informando ao usuário o fim da operação 
         */
        private function completeHandler(event:Event):void 
        {
            _progressBar.label = "Carregamento Completo";
            _myTimer1.start();
        }
        
		public function timerHandler1(event:TimerEvent):void 
		{			
            PopUpManager.removePopUp(_titleWindow);
		}
        
        /**
         * Após o arquivo selecionado o upload é executado. 
         */
        private function selectHandler(event:Event):void 
        {
            _request = new URLRequest();
            _request.url = UPLOAD_URL;
            _request.method = URLRequestMethod.POST;
            openWindow();
            
            _selecionado = true;
        }

		public function get Selecionado():Boolean
		{
			return _selecionado;
		}
	
		public function Upload():void
		{
            _fileReference.upload(_request);
		}

		public function get Nome():String
		{
			return _fileReference.name;
		}

        /**
         * Abre popUp com a progressBar. 
         */
        private function openWindow():void
        {
            _titleWindow = new TitleWindow();
            _titleWindow.title = "Carregando Arquivo";
            _titleWindow.width = 250;
            _titleWindow.height = 80;
            _progressBar.percentHeight = 100;
            _progressBar.percentWidth = 100;
            _titleWindow.addChild(_progressBar); 
            PopUpManager.addPopUp(_titleWindow, (Application.application as DisplayObject), true);
            _titleWindow.x = (Application.application.width - _titleWindow.width) / 2; 
            _titleWindow.y = (Application.application.height - _titleWindow.height) / 2;
        }
        
        public function Browse():void
        {
        	_fileReference.browse();
        }
    }
}